<template>
  <div class="question-container">
    <el-card class="question-card">
      <!-- 顶部信息栏 -->
      <div class="header">
        <div class="user-info">
          <el-tag type="info" size="large">
            <el-icon><User /></el-icon>
            <span class="username">{{ userInfo.username }}</span>
          </el-tag>
        </div>
        <div class="progress-container">
          <div class="progress-wrapper">
            <el-progress 
              :percentage="answeredPercentage" 
              :stroke-width="12"
              :show-text="false"
              color="#409EFF"
              class="progress-bar"
            />
          </div>
          <div class="progress-text">
            <span>已完成 {{ answeredCount }} / {{ questions.length }} 题 ({{ answeredPercentage }}%)</span>
          </div>
        </div>
      </div>

      <!-- 题目内容区域 -->
      <div class="question-content">
        <h3 class="question-text">{{ currentQuestion.questionText }}</h3>
        
        <el-radio-group 
          v-model="answers[currentIndex]" 
          class="options-group"
          @change="handleOptionChange"
        >
          <el-radio 
            :value="'a'" 
            class="option-item"
          >
            <span class="option-letter">A</span> 
            <span class="option-text">{{ currentQuestion.optionA }}</span>
          </el-radio>
          <el-radio 
            :value="'b'" 
            class="option-item"
          >
            <span class="option-letter">B</span> 
            <span class="option-text">{{ currentQuestion.optionB }}</span>
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 导航按钮 -->
      <div class="navigation">
        <el-button 
          :disabled="currentIndex === 0" 
          @click="prevQuestion"
          class="nav-button"
          plain
          round
        >
          <el-icon><ArrowLeft /></el-icon>
          <span>上一题</span>
        </el-button>
        
        <el-button 
          v-if="currentIndex < questions.length - 1"
          type="primary" 
          :disabled="!answers[currentIndex]"
          @click="nextQuestion"
          class="nav-button"
          round
        >
          <span>下一题</span>
          <el-icon><ArrowRight /></el-icon>
        </el-button>
        
        <el-button 
          v-else
          type="success" 
          :disabled="submitting || !isAllAnswered"
          @click="submitTest"
          class="submit-button"
          :loading="submitting"
          round
        >
          <el-icon v-if="!submitting"><Finished /></el-icon>
          <span>{{ submitting ? '提交中...' : '提交测试' }}</span>
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, ArrowLeft, ArrowRight, Finished } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

// 用户信息
const userInfo = ref(JSON.parse(localStorage.getItem('xm-pro-user')) || {})

// 题目数据
const questions = ref([])
const answers = ref([])
const currentIndex = ref(0)
const submitting = ref(false)

const router = useRouter()

// 计算已回答的题目数量
const answeredCount = computed(() => {
  return answers.value.filter(answer => answer !== null).length
})

// 计算已回答百分比
const answeredPercentage = computed(() => {
  return questions.value.length > 0 
    ? Math.round(answeredCount.value / questions.value.length * 100)
    : 0
})

// 检查是否所有题目都已回答
const isAllAnswered = computed(() => {
  return answers.value.every(answer => answer !== null)
})

// 获取题目数据
const fetchQuestions = async () => {
  try {
    const res = await request.get('/mbtiquestion/list')
    if (res && res.data) {
      questions.value = res.data
      answers.value = new Array(res.data.length).fill(null)
    } else {
      ElMessage.error('获取题目数据格式不正确')
    }
  } catch (error) {
    ElMessage.error('获取题目失败')
    console.error('获取题目失败:', error)
  }
}

// 当前题目
const currentQuestion = computed(() => {
  return questions.value[currentIndex.value] || {}
})

// 选项变化处理
const handleOptionChange = (value) => {
  answers.value[currentIndex.value] = value
}

// 上一题
const prevQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++
  }
}

// 提交测试
const submitTest = async () => {
  if (!isAllAnswered.value) {
    ElMessage.warning('请完成所有题目后再提交')
    return
  }

  try {
    submitting.value = true
    
    const payload = {
      userId: userInfo.value.userId,
      answers: answers.value.map((answer, index) => ({
        questionId: questions.value[index].questionId,
        choice: answer
      }))
    }
    
    const res = await request.post('/mbtitest/submit', payload)
    
    if (res && res.code === '200') {
      ElMessage.success('提交成功')
      router.push(`/mbti/${res.data.mbtiType}`)
    } else {
      ElMessage.error(res.msg || '提交失败')
    }
  } catch (error) {
    ElMessage.error('提交过程中发生错误')
    console.error('提交错误:', error)
  } finally {
    submitting.value = false
  }
}

// 初始化获取题目
onMounted(() => {
  if (userInfo.value.userId) {
    fetchQuestions()
  } else {
    ElMessage.warning('请先登录')
    router.push('/login')
  }
})
</script>

<style scoped>
.question-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.question-card {
  width: 100%;
  max-width: 800px;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.header {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 30px;
}

.user-info {
  display: flex;
  justify-content: flex-start;
}

.user-info .el-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  font-size: 16px;
  background-color: #f0f2f5;
  border-color: #e4e7ed;
}

.user-info .el-icon {
  font-size: 18px;
}

.username {
  font-weight: 500;
  color: #606266;
}

.progress-container {
  width: 100%;
}

.progress-wrapper {
  width: 100%;
  margin-bottom: 8px;
}

.progress-bar {
  width: 100%;
  border-radius: 6px;
}

.progress-text {
  text-align: center;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.question-content {
  margin: 40px 0;
}

.question-text {
  color: #303133;
  font-size: 20px;
  line-height: 1.6;
  margin-bottom: 30px;
  text-align: center;
}

.options-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 40px;
}

.option-item {
  display: flex;
  align-items: center;
  width: 100%;
  min-height: 72px;
  padding: 16px 20px;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
  margin: 0 !important;
  box-sizing: border-box;
  cursor: pointer;
}

.option-item:hover {
  border-color: #409EFF;
  background-color: #f5f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.option-item.is-checked {
  border-color: #409EFF;
  background-color: #ecf5ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.option-letter {
  flex-shrink: 0;
  font-weight: bold;
  color: #409EFF;
  margin-right: 16px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ecf5ff;
  border-radius: 50%;
  font-size: 16px;
}

.option-text {
  flex-grow: 1;
  text-align: left;
  word-break: break-word;
  font-size: 16px;
  line-height: 1.5;
}

.navigation {
  display: flex;
  justify-content: space-between;
  margin-top: 50px;
}

.nav-button, .submit-button {
  min-width: 140px;
  height: 44px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.submit-button {
  min-width: 160px;
}

@media (max-width: 768px) {
  .question-card {
    padding: 24px;
    border-radius: 12px;
  }
  
  .header {
    gap: 16px;
  }
  
  .question-text {
    font-size: 18px;
    margin-bottom: 24px;
  }
  
  .option-item {
    min-height: 64px;
    padding: 14px 16px;
  }
  
  .option-letter {
    width: 28px;
    height: 28px;
    margin-right: 12px;
  }
  
  .option-text {
    font-size: 15px;
  }
  
  .navigation {
    margin-top: 40px;
    flex-direction: column;
    gap: 12px;
  }
  
  .nav-button, .submit-button {
    width: 100%;
  }
}
</style>